<template>
    <div>
        <phone-book-header></phone-book-header>
        <phone-book-search :phoneBooks="phoneBooks"></phone-book-search>
        <phone-book-list :letter="letter" :phoneBooks="phoneBooks"></phone-book-list>
        <phone-book-alphabet :phoneBooks="phoneBooks" @handleClickLetter="handleClickLetter"></phone-book-alphabet>
    </div>
</template>

<script>
import axios from 'axios'
import PubSub from 'pubsub-js'
import PhoneBookHeader from '@/components/home/Header'
import PhoneBookSearch from '@/components/home/Search'
import PhoneBookList from '@/components/home/List'
import PhoneBookAlphabet from '@/components/home/Alphabet'

export default {
    name: 'PhoneBook',
    data() {
        return {
            phoneBooks: {},
            letter: ''
        }
    },
    components: {
        PhoneBookHeader,
        PhoneBookSearch,
        PhoneBookList,
        PhoneBookAlphabet
    },
    methods: {
        refreshToken() {
            axios.get('token/refreshToken')
                    .then(response => {
                        localStorage.setItem('token', response.data.token);
                    })
                    .catch(error => {
                        console.log(error)
                    })
        },
        getPhoneBooks() {
            axios.get('phoneBook/loadAll')
                    .then(response => {
                        console.log('getPhoneBooks:', response)
                        this.phoneBooks = response.data.data
                    })
                    .catch(error => {
                        console.log(error)
                    })
        },
        handleClickLetter(letter) {
            this.letter = letter
        }
    },
    mounted() {
        axios.defaults.baseURL = 'http://localhost:8080/'
        axios.defaults.headers.common['token'] = localStorage.getItem("token")
        // setInterval(this.refreshToken, 1000 * 3); // 测试 10秒钟刷新一次token
        setInterval(this.refreshToken, 1000 * 60 * 10); // 正式 10分钟刷新一次token
        this.getPhoneBooks() // 加载所有电话簿信息
        PubSub.subscribe('refreshPhoneBook', (msg, data) => {
            console.log('收到消息 refreshPhoneBook',msg,data)
            this.getPhoneBooks()
        })
    }
}
</script>

<style scoped>

</style>
